package tool.soft

import java.io.File
import command.CommandExec
import dao._
import models.Tables
import org.joda.time.DateTime
import play.api.mvc.{AnyContent, Request}
import play.twirl.api.Html
import shared.Pojo._
import tool.Pojo._
import shared.Pojo._
import tool._
import tool.plot._
import tool.soft.AllSoft.SoftBT
import implicits.Implicits._
import models.Tables._
import play.api.data.FormBinding
import play.api.i18n.Messages
import utils.Utils
import upickle.default._

/**
 * Created by yz on 15/9/2020
 */
object BasicSoft extends BasicSoftT with SoftBT {

  override def getFileInfos(workspaceDir: File, index: Int)(implicit matrixFileDataDao: MatrixFileDataDao, messages: Messages): List[FileInfoData] = {
    List(
      FileInfoData("Basic_Statistics.csv", messages("basicStatistics")),
      FileInfoData("Class_Barplot_by_Group.csv", messages("classBarplotByGroup")),
      FileInfoData("Class_Barplot_by_Group.pdf", messages("classBarplotByGroup")),
      FileInfoData("Class_Barplot_by_Sample.pdf", messages("classBarplotBySample")),
      FileInfoData("Class_Barplot_by_Group_Test.csv", messages("classBarplotByGroupTest")),
    )
  }

  override def produceConfigFile(workspaceDir: File, index: Int)(implicit request: Request[AnyContent], formBinding: FormBinding) = {
    super.produceConfigFile(workspaceDir, index)
    data.lines().toTxtFile(Tool.getCalculateConfigTxtFile(workspaceDir))
    Utils.t2ConfigFile(workspaceDir, data)
  }

  override def producePlotConfigFile(workspaceDir: File, index: Int): Any = {
    Tool.producePlotConfigFile(AllPlotData(), SampleBar, workspaceDir)
    Tool.producePlotConfigFile(AllPlotData(), GroupBar, workspaceDir)
  }

  override def getResultHtml(missionId: Int)(implicit request: Request[AnyContent], messages: Messages): Html = {
    views.html.user.mission.basicResult(missionId)
  }

  def getArg(implicit request: Request[AnyContent], messages: Messages, formBinding: FormBinding): ujson.Value = {
    val groupNum = Tool.getGroupNum(userId, data.groupFile)
    val isPairedStr = if (data.isPaired.isDefined) messages("yes") else messages("no")
    if (groupNum == 2) {
      ujson.Obj(messages("analysisMethod") -> Tool.getMethod(data.method),
        messages("fCCalculationMethod") -> Tool.getFcMethod(data.fcMethod), messages("paired") -> isPairedStr)
    } else {
      ujson.Obj(messages("analysisMethod") -> Tool.getMulMethod(data.mulMethod))
    }
  }

  override def produceInput(workspaceDir: File, resultDir: File)(implicit dao: MyDao): Unit = {
    val rawDataFile = new File(workspaceDir, "AllMet_Raw.txt")
    Tool.produceKeggInfoFile(rawDataFile, workspaceDir)
  }

  override def getCommandData(workspaceDir: File, resultDir: File, index: Int):  List[CommandData] = {
    val solutionFile = new File(Tool.dataDir, "color_solution/color_solution_1.txt")
    val groupFile = new File(workspaceDir, "group.txt")
    val rawDataFile = new File(workspaceDir, "AllMet_Raw.txt")
    val annoFile = new File(workspaceDir, "AllMet_with_Anno.txt")
    val command =
      s"""
         |${Tool.rScript} ${new File(Tool.rPath, "anno.R").unixPath}
         |${Tool.rScript} ${new File(Tool.rPath, "produce_sample_color.R").unixPath} --g ${groupFile.unixPath}  --solution ${solutionFile.unixPath}
         |${Tool.rScript} ${new File(Tool.rPath, "produce_meta_color.R").unixPath} --i ${annoFile.unixPath}
         |${"Rscript".condaPath()} ${new File(Tool.rPath, "group_stat.R").unixPath} --i ${annoFile.unixPath}
         |${"Rscript".condaPath()} ${new File(Tool.rPath, "meta_relative_abundance_plot.R").unixPath} --i ${annoFile.unixPath}
         |${"Rscript".condaPath()} ${new File(Tool.rPath, "meta_relative_abundance_sum_test.R").unixPath} --i ${annoFile.unixPath}
         |${"Rscript".condaPath()} ${new File(Tool.rPath, "meta_relative_abundance_sum_plot.R").unixPath} --i ${annoFile.unixPath}
         |convert  -density 300 Class_Barplot_by_Sample.pdf  Class_Barplot_by_Sample.png
         |convert  -density 300 Class_Barplot_by_Group.pdf  Class_Barplot_by_Group.png
           """.stripMargin
    List(CommandData(workspaceDir, List(command)))
  }

  override def getHtml(missionName: String, missionId: Option[Int])(implicit request: Request[AnyContent], messages: Messages): Html = {
    views.html.user.soft.basic(missionName, missionId)
  }

  override def getMission(implicit request: Request[AnyContent], matrixFileDataDao: MatrixFileDataDao, messages: Messages, formBinding: FormBinding): Tables.MissionRow = {
    val initInputs = List(data.file, data.groupFile)
    val hasLibInputs =initInputs
    val argJson = getArg
    MissionRow(id = 0, missionName = s"${data.missionName}", kind = nameStr, userId = userId,
      startTime = new DateTime(), state = "preparing", arg = argJson, input = hasLibInputs)
  }

  override def produceInputFile(workspaceDir: File)(implicit request: Request[AnyContent], dao: MyDao, formBinding: FormBinding): Any = {
    val rawDataFile = new File(workspaceDir, "AllMet_Raw.txt")
    Tool.produceRawDataFile(userId, data.file, rawDataFile)
    val groupFile = new File(workspaceDir, "group.txt")
    Tool.produceRawGroupFile(userId, data.groupFile, rawDataFile, groupFile)
  }

  override def data(implicit request: Request[AnyContent], formBinding: FormBinding) = {
    FormTool.basicForm.bindFromRequest().get
  }


}

